package com.tongtong.middleware.blockchain.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tongtong.middleware.blockchain.entity.TblUserChainAccountEntity;
import com.tongtong.middleware.blockchain.mapper.TblUserChainAccountMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.web3j.utils.Numeric;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class TblUserChainAccountService  extends ServiceImpl<TblUserChainAccountMapper, TblUserChainAccountEntity> {
    /**
     * 根据用户id查询是否存在记录
     */
    public TblUserChainAccountEntity findByAppUserId(String appUserId) {
        QueryWrapper<TblUserChainAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_user_id", appUserId);
        return baseMapper.selectOne(queryWrapper);
    }
    // 插入用户信息
    @Async
    public void UpdateByAppUserId(String appUserId, String account, String salt) {
        UpdateWrapper<TblUserChainAccountEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("app_user_id", appUserId).set("chain_name", "武汉链")
                .set("chain_id", 5555).set("chain_account", account).set("salt", salt);
        baseMapper.update(updateWrapper);
    }

    public String getPrivateKey(String appUserId) {
        TblUserChainAccountEntity tblUserChainAccountEntity = findByAppUserId(appUserId);
        String data = appUserId + "eth-666" + tblUserChainAccountEntity.getSalt();
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA3-256");
        } catch (NoSuchAlgorithmException e) {
            log.error("createAccount:Exception=>{}", e);
        }
        assert digest != null;
        byte[] hash = digest.digest(data.getBytes());

        // 将私钥字节数组转换为十六进制字符串

        return Numeric.toHexStringNoPrefix(hash);
    }

}
